<?php
/**
 * Class file for class SwiftORM
 *
 * @package    SwiftORM
 * @author     Stephen Gray
 * @copyright  Stephen Gray
 * @license    http://www.gnu.org/licenses/gpl.txt
 * @link       http://code.google.com/p/swiftorm
 */

/**
 * SwiftORM
 *
 * mainly used in the autloader, provides
 * util functions to check various values
 * against the database
 *
 * @package    SwiftORM
 * @author     Stephen Gray
 * @copyright  Stephen Gray
 * @license    http://www.gnu.org/licenses/gpl.txt
 * @link       http://code.google.com/p/swiftorm
 */
class SwiftORM extends SwiftBase
{
    /**
     * $_tableList
     *
     * array of all tables from current database
     *
     * @var    array
     * @access protected
     */
    protected $_tableList = array();
   
    /**
     * void __construct ( array $config )
     *
     * run parent constructor then save list
     * of tables
     *
     * @param  array $config
     * @return void
     * @access public
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
        
        /**
         * store a table list
         */
        $tables = $this->_query('SHOW TABLES;');
        foreach ($tables as $values)
        {
            $this->_tableList[] = $values['Tables_in_'.$config['database']['name']];
        }
    }

    /**
     * bool checkForTable ( string $tableName )
     *
     * check if a table exists in the current database
     *
     * @var    string $tableName
     * @return bool
     * @access public
     */
    public function checkForTable($tableName)
    {
        return in_array($tableName, $this->_tableList);
    }

    /**
     * SwiftTable getTable ( string $modelName )
     *
     * SwiftTable factory
     *
     * @param  string      $modelName
     * @return SwiftTable
     * @access public
     * @static
     */
    public static function getTable($modelName)
    {
        global $ormObj;
        $pattern = "/(.)([A-Z])/"; 
        $replacement = "\\1 \\2";
        $tableName = strtolower(str_replace(' ', '_', preg_replace($pattern, $replacement, $modelName)));
        if ($ormObj->checkForTable($tableName))
        {
            return new SwiftTable($modelName, $ormObj->getConnection(), true);
        }
        else
        {
            throw new Exception('Table \''.$tableName.'\' not found');
        }
    }

    public static function rawQuery($query)
    {
        global $ormObj;
        return $ormObj->_query($query);
    }
}
